import "reflect-metadata";
import path from "path";
import fs from "fs";

import Crawler from "../utils/crawler";
import WalkerAnalyzer from "../utils/walkerAnalyzer";

import { NextFunction, Request, Response } from "express";
import { get } from "../decorator/request";
import { use } from "../decorator/use";
import { controller } from "../decorator/controller";
import { getResponseData } from "../utils/util";

const checkLogin = (req: Request, res: Response, next: NextFunction): void => {
  console.log("in checklogin middleware");
  const isLogin = !!(req.session ? req.session.login : false);
  if (isLogin) {
    next();
  } else {
    res.json(getResponseData(null, "Login first"));
  }
};

const testMiddleware = (
  req: Request,
  res: Response,
  next: NextFunction
): void => {
  console.log("in test middleware");
  next();
};

@controller
class CrowllerController {
  @get("/getdata")
  @use(checkLogin)
  @use(testMiddleware)
  getData(req: Request, res: Response): void {
    const url = "http://www.dell-lee.com/typescript/demo.html";
    const filePath = path.resolve(__dirname, "../../data/course.json");
    const analyzer = WalkerAnalyzer.getInstance();
    new Crawler(url, filePath, analyzer);
    res.json(getResponseData(true));
  }
  @get("/showdata")
  @use(checkLogin)
  @use(testMiddleware)
  showdata(req: Request, res: Response): void {
    try {
      const position = path.resolve(__dirname, "../../data/course.json");
      const result = fs.readFileSync(position, "utf-8");
      res.json(getResponseData(JSON.parse(result)));
    } catch (e) {
      res.json(getResponseData(false, "No data yet!"));
    }
  }
}
